package servlet;

import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ASUS
 * Date: 2024-01-16
 * Time: 14:59
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.读取参数中的用户名和密码
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 验证一下参数是否合理
        if(username == null || username.length() == 0 || password == null || password.length() == 0){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("输入的用户名或者密码为空!!");
            return;
        }
        //2.查询数据库
        UserDao userDao = new UserDao();
        User user = userDao.getUserByName(username);
        if(user == null){
            //用户名不存在
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("输入的用户名或密码错误!!");
            return;
        }
        if(!password.equals(user.getPassword())){
            //密码不正确
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("输入的用户名或密码错误!!");
            return;
        }
        //3.创建会话
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);

        //4.跳转到主页
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过这个方法，反馈用户的登录状态
        //简单的方式就是看会话是否存在
        //此处更严格的方式--不仅要求会话存在，还要求会话中要保存user对象
        //这样的设定是为了后续实现“退出登录”做铺垫
        HttpSession session = req.getSession(false);
        if(session == null){
            //会话不存在，用户属于未登录状态
            resp.setStatus(403);
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            //user对象也不存在，同样属于未登录状态
            resp.setStatus(403);
            return;
        }
        //两个都存在，返回200--默认值【写不写都行】
        resp.setStatus(200);
    }
}
